package com.example.springboot;

import com.example.springboot.user.User;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Map;


@RestController
@SpringBootApplication
public class SpringbootApplication {
    ArrayList<User> userList = new ArrayList<>();
    User u1 = new User("Elysia", "123456", "123456" , "教师");
    User u2 = new User("ShenYue", "2129403101", "123456" , "学生");

    public SpringbootApplication() {
        userList.add(u1);
        userList.add(u2);
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringbootApplication.class, args);
    }

    @GetMapping
    public String health() {
        return "SUCCESS";
    }

    @CrossOrigin
    @RequestMapping("/getUserList")
    public ArrayList<User> getUserList() {
        return userList;
    }

    @CrossOrigin
    @RequestMapping("/checkUser")
    public boolean checkUser(@RequestBody User u) {
        for(int i = 0;i < userList.size(); i++){
            User p = userList.get(i);
            if (u.uid.equals(p.uid) && u.pwd.equals(p.pwd) && u.identity.equals(p.identity)){
                return true;
            }
        }
        return false;
    }

    @CrossOrigin
    @RequestMapping("/getUserInfo")
    public User getUser(@RequestBody User u) {
        for(int i = 0;i < userList.size(); i++){
            User p = userList.get(i);
            if (u.uid.equals(p.uid) && u.pwd.equals(p.pwd) && u.identity.equals(p.identity)){
                return p;
            }
        }
        return null;
    }

//    @CrossOrigin
//    @PostMapping("/changePwd")
//    public boolean changePwd(@RequestBody Map<String, String> payload) {
////        System.out.println("Payload: " + payload);
//        String uid = payload.get("uid");
//        String oldPwd = payload.get("oldPwd");
//        String newPwd = payload.get("newPwd");
//
//        for (int i = 0; i < userList.size(); i++) {
//            User p = userList.get(i);
//            if (p.uid.equals(uid) && p.pwd.equals(oldPwd)) {
//                p.pwd = newPwd;
//                return true;
//            }
//        }
//        return false;
//    }

    @CrossOrigin
    @RequestMapping("/changePwd")
    public boolean changePwd(@RequestParam String uid,@RequestParam String oldPwd,@RequestParam String newPwd) {
        for (int i = 0; i < userList.size(); i++) {
            User p = userList.get(i);
            if (p.uid.equals(uid) && p.pwd.equals(oldPwd)) {
                p.pwd = newPwd;
                return true;
            }
        }
        return false;
    }
}


